import {
	createStore
} from 'vuex';
import apis from '@/apis/index.js';
import w_md5 from '@/js_sdk/js-md5/w_md5.js';
import $U from '@/common/util.js';
import env from '@/env.js';
import envConfig from '@/env_config';
const $C = envConfig[env];

const md5 = (data) => {
	return w_md5.hex_md5_32(data);
}

export default createStore({
	state: {
		$C,
		user: {},
		token: '',
		cloud: false,
		sms: [],
		targetEmail: '',
		query: {
			limit: 10,
			offset: 0
		},
		cloudRecords: {
			rows: [],
			count: 0
		}
	},
	getters: {

	},
	mutations: {
		setUser(state, payload) {
			state.user = payload;
		},
		setToken(state, payload) {
			state.token = payload;
		},
		setSms(state, payload) {
			state.sms = payload;
		},
		setCloud(state, payload) {
			state.cloud = payload;
		},
		setCloudRecords(state, payload) {
			state.cloudRecords = payload;
		},
		setQuery(state, payload) {
			state.query = payload;
		},
		setTargetEmail(state, payload) {
			state.targetEmail = payload;
		}
	},
	actions: {
		registry({
			commit
		}, data) {
			uni.showLoading({
				title: '注册中...'
			});
			apis.registry({
				...data,
				password: md5(data.password),
				name: data.phone,
				age: Math.floor(Math.random() * 100)
			}).then(res => {
				uni.hideLoading();
				const {
					success,
					data,
					msg
				} = res;
				if (!success) {
					uni.showToast({
						title: msg,
						icon: "error"
					});
					return;
				}

				uni.showToast({
					title: '注册成功',
					duration: 1400
				});

				const timer = setTimeout(() => {
					uni.redirectTo({
						url: '/pages/login/login'
					});
					clearTimeout(timer);
				}, 1500);
			}).catch(e => {
				uni.showToast({
					title: '注册失败，请稍后再试'
				});
			});
		},
		login({
			commit
		}, payload) {
			uni.showLoading({
				title: '登录中...'
			});
			const {
				phone = '', password = ''
			} = payload;
			apis.login({
					phone,
					password: md5(password)
				})
				.then(res => {
					uni.hideLoading();
					const {
						success,
						data,
						msg
					} = res;
					// 登录成功
					if (success && data) {
						uni.showToast({
							title: msg,
							icon: 'success',
							duration: 1000
						});
						const {
							id = '', phone = '', token = '',
								email = ''
						} = data;

						const user = {
							id,
							phone,
							email
						};

						commit('setUser', user);
						commit('setToken', token);
						uni.setStorageSync('user', JSON.stringify(user));
						uni.setStorageSync('token', JSON.stringify(token));

						const timer = setTimeout(() => {
							$U.switchTab('index');
							clearTimeout(timer);
						}, 1000)

						return;
					}
					uni.showToast({
						title: msg,
						icon: 'error'
					});
				})
				.catch(e => {
					uni.hideLoading();
					uni.showToast({
						title: '登录失败，请稍后再试',
						icon: 'error'
					});
					console.log('【login - error】-- ', e);
				});
		},
		initUser({
			commit
		}) {
			console.log('【Initializing...】');
			const user = uni.getStorageSync('user');
			const token = uni.getStorageSync('token');
			const sms = uni.getStorageSync('sms');
			const targetEmail = uni.getStorageSync('targetEmail');

			if (!user || !token) {
				$U.redirectTo('login');
				return;
			}
			if (user) commit('setUser', JSON.parse(user));
			if (token) commit('setToken', JSON.parse(token));
			if (sms) commit('setSms', sms);
			if (targetEmail) commit('setTargetEmail', targetEmail);
		},
		createSms({
			commit,
			state
		}, data) {
			console.log('【Create sms data】', data);
			const _sms = state.sms;
			_sms.unshift(data);
			commit('setSms', _sms);
			uni.setStorageSync('sms', _sms);
			apis.createSms(data, {
					token: state.token
				})
				.then(res => {
					console.log('【Create sms res】', res);
				})
				.catch(e => {
					console.log('【Create sms error】', e);
				});
		},
		getSms({
			state
		}, data) {
			const {
				token
			} = state;
			return apis.getSms(data, {
				token: token
			});
		},
		getCloudRecords({
			state,
			dispatch,
			commit
		}, data) {
			const {
				query
			} = state;

			uni.showLoading({
				title: '加载中...'
			});

			dispatch('getSms', query)
				.then(res => {
					// 短震动 15ms
					uni.vibrateShort();
					uni.hideLoading();
					const {
						success,
						data,
						message
					} = res;

					if (success && data) {
						const rows = [
							...state.cloudRecords.rows,
							...data.rows
						];
						const count = data.count;
						commit('setCloudRecords', {
							rows,
							count
						});
					}
				})
				.catch(e => {
					uni.hideLoading();
					console.log('dispatch get sms error: ', e);
				});
		}
	}
})
